package com.xiangban.yanglaodajie_admin.service;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.xiangban.yanglaodajie_admin.dao.GoodsMapper;
import com.xiangban.yanglaodajie_admin.dao.ShopMapper;
import com.xiangban.yanglaodajie_admin.entity.*;
import com.xiangban.yanglaodajie_admin.entity.dto.OrdersDto;
import com.xiangban.yanglaodajie_admin.entity.dto.PermissionMenuDto;
import com.xiangban.yanglaodajie_admin.entity.dto.ShopDto;
import com.xiangban.yanglaodajie_admin.entity.dto.ShopLoginDto;
import com.xiangban.yanglaodajie_admin.entity.res.ApiResult;
import com.xiangban.yanglaodajie_admin.entity.res.ApiResultCode;
import com.xiangban.yanglaodajie_admin.exception.BizException;
import com.xiangban.yanglaodajie_admin.utils.*;
import io.netty.handler.codec.compression.Bzip2Decoder;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.xml.crypto.Data;
import javax.servlet.http.HttpServletRequest;
import java.text.SimpleDateFormat;
import java.util.*;

import static com.xiangban.yanglaodajie_admin.utils.CommonUtils.BizEmpty;
import static com.xiangban.yanglaodajie_admin.utils.CommonUtils.compare;
import static com.xiangban.yanglaodajie_admin.utils.RedisUtil.*;


/**
 * @Author Mr. MaYaYun
 * @Data 2021/5/28 10:02
 */
@Service
public class ShopService {

    @Autowired
    private ShopMapper shopMapper;
    @Autowired
    private PageUtil pageUtil;
    @Autowired
    private RedisUtil redisUtil;
    @Autowired
    private CommonUtils commonUtils;
    @Autowired
    private HttpServletRequest request;
    @Autowired
    private GoodsMapper goodsMapper;

    public PageInfo<OrdersDto> getShopOrders(OrdersDto ordersDto) {//参数：商家id、订单状态、配送的订单的配送状态
        if (commonUtils.getShopId(request) == null){
            throw new BizException(ApiResultCode.FLAG_FAIL_VOUCHER);
        }
        ordersDto.setShopId(Integer.parseInt(commonUtils.getShopId(request)));
        PageHelper.startPage(pageUtil.getPage().getPageNum(),pageUtil.getPage().getPageSize());
        if ( ordersDto.getValue2() != null &&  ordersDto.getValue2().size() >1){
            List<String> value2 = ordersDto.getValue2();
            for (int i = 0; i < value2.size(); i++) {
//                Date parse = new SimpleDateFormat("yyyy-MM-dd").parse(value2.get(0));
//                Date date = new Date(value2.get(0));
                ordersDto.setDate1(value2.get(0));
                ordersDto.setDate2(value2.get(1));
            }
        }
        List<OrdersDto> ordersList = shopMapper.getOrdersList(ordersDto);
        return new PageInfo<>(ordersList);
    }

    public Object getShopOrdersInfo(Orders orders) {
        if (BizEmpty(orders.getOrderNumber())){
            throw new BizException(ApiResultCode.PARAMETER_DEFICIENCY);
        }
        OrdersDto ordersDto = shopMapper.selectOrdersInfo(orders);//订单详情

        if (ordersDto == null){
            throw new BizException(ApiResultCode.ORDERS_NULL);
        }
        String goodSku = ordersDto.getGoodSku();
        JSONArray objects = JSON.parseArray(goodSku);
        ObjectMapper objectMapper = new ObjectMapper();
        ArrayList<Object> list = new ArrayList<>();
        for (int i = 0; i < objects.size(); i++) {
            Object o = objects.get(i);
            Map map1 = objectMapper.convertValue(o, Map.class);
            int goodsId = (int) map1.get("goodsId");
            Goods goods = new Goods();
            goods.setGoodsId(goodsId);
            Goods info = goodsMapper.findGoodsByGoodsId(goods);
            map1.put("image",info.getLogo());
            list.add(map1);
        }
        ordersDto.setGoodSkuDto(list);
        ordersDto.setGoodSku(null);
        return ordersDto;
    }


    public Map<String,Object> OrdersClassifyNumber(Orders orders) {//参数：商家id
        if (commonUtils.getShopId(request) == null){
            throw new BizException(ApiResultCode.FLAG_FAIL_VOUCHER);
        }
        orders.setShopId(Integer.parseInt(commonUtils.getShopId(request)));
        HashMap<String, Object> map = new HashMap<>();
        ShopDto waitTakes = shopMapper.findWaitTakes(orders);//查询待配送数量
        if (waitTakes == null){
            map.put("waitTakes",0);
        }else {
            map.put("waitTakes",waitTakes.getWaitTakes());
        }
        ShopDto waitConfirm = shopMapper.findWaitConfirm(orders);//查询待确认数量
        if (waitConfirm == null){
            map.put("waitConfirm",0);
        }else {
            map.put("waitConfirm",waitConfirm.getWaitConfirm());
        }
        ShopDto waitRefund = shopMapper.findWaitRefund(orders);//查询待退款数量
        if (waitRefund == null){
            map.put("waitRefund",0);
        }else {
            map.put("waitRefund",waitRefund.getWaitRefund());
        }
        ShopDto waitDestroy = shopMapper.findWaitDestroy(orders);//查询待核销数量
        if (waitDestroy == null){
            map.put("waitDestroy",0);
        }else {
            map.put("waitDestroy",waitDestroy.getWaitDestroy());
        }
        return map;
    }

    /**
     * 修改订单配送状态
     * @param orders
     * @return
     */
    public void updateStatus(Orders orders) {//参数：商家id、订单编号、订单配送状态
        if (BizEmpty(orders.getOrderNumber())){
            throw new BizException(ApiResultCode.PARAMETER_DEFICIENCY);
        }
        if (BizEmpty(orders.getTakesState())){
            throw new BizException(ApiResultCode.PARAMETER_DEFICIENCY);
        }
        shopMapper.updateStatus(orders);
    }

    public Map<String,Object> todayIntegral(Orders orders) {//参数：商家id、查询的时间
        if(commonUtils.getShopId(request) == null){
            throw new BizException(ApiResultCode.FLAG_FAIL_VOUCHER);
        }
        orders.setShopId(Integer.parseInt(commonUtils.getShopId(request)));
        HashMap<String, Object> map = new HashMap<>();
        orders.setUpdateTime(new SimpleDateFormat("yyyy-MM-dd").format(new Date()).replace("-", ""));
        OrdersDto todayIntegral = shopMapper.findTodayIntegral(orders);
        if (todayIntegral == null){
            map.put("todayIntegral",0);
        }else {
            map.put("todayIntegral",todayIntegral.getSumGoodsPrice());
        }
        OrdersDto ordersNumber = shopMapper.findOrdersNumber(orders);
        if (ordersNumber == null){
            map.put("todayOrdersNumber",0);
        }else {
            map.put("todayOrdersNumber",ordersNumber.getSumOrdersNumber());
        }
        OrdersDto allOrderPrice = shopMapper.findAllOrderPrice(orders);
        if (allOrderPrice == null){
            map.put("allOrderPrice",0);
        }else {
            map.put("allOrderPrice",allOrderPrice.getAllSumGoodsPrice());
        }
        return map;
    }

    public ShopDto getShopInfo(Shop shop) {//参数：商家id
        if (commonUtils.getShopId(request) == null){
            throw new BizException(ApiResultCode.FLAG_FAIL_VOUCHER);
        }
        shop.setShopId(Integer.parseInt(commonUtils.getShopId(request)));
        ShopDto shopDto = shopMapper.selectShopInfo(shop);
        if (shopDto !=null){
            shopDto.setSynopsisImages((List<String>) JSON.parse(shopDto.getSynopsisImage()));
            shopDto.setSynopsisImage(null);
            String[] split1 = new String[0];
            String[] split2 = new String[0];
            String[] split3 = new String[0];
            if (shopDto.getService() !=null && !shopDto.getService().equals("") ){
                split1 = shopDto.getService().split(",");
            }
            if (shopDto.getShopLabel() !=null && !shopDto.getShopLabel().equals("")){
                split2 = shopDto.getShopLabel().split(",");
            }
            if (shopDto.getSuperiorService() !=null && !shopDto.getSuperiorService().equals("") ){
                split3 = shopDto.getSuperiorService().split(",");
            }
            ArrayList<String> ServiceDto = new ArrayList<>(Arrays.asList(split1));
            ArrayList<String> ShopLabelDto = new ArrayList<>(Arrays.asList(split2));
            ArrayList<String> SuperiorServiceDto = new ArrayList<>(Arrays.asList(split3));

            shopDto.setServiceDto(ServiceDto);
            shopDto.setShopLabelDto(ShopLabelDto);
            shopDto.setSuperiorServiceDto(SuperiorServiceDto);
        }
        return shopDto;
    }

    public void updateShopInfo(Shop shop) {//参数：商家id
        if (commonUtils.getShopId(request) == null){
            throw new BizException(ApiResultCode.FLAG_FAIL_VOUCHER);
        }
        if (BizEmpty(shop.getShopName())){
            throw new BizException(ApiResultCode.PARAMETER_DEFICIENCY);
        }
        if (BizEmpty(shop.getWorkTime())){
            throw new BizException(ApiResultCode.PARAMETER_DEFICIENCY);
        }
        if (BizEmpty(shop.getPhone())){
            throw new BizException(ApiResultCode.PARAMETER_DEFICIENCY);
        }
        shop.setShopId(Integer.parseInt(commonUtils.getShopId(request)));
        shopMapper.updateShopInfo(shop);
    }

    public ApiResult<Object> login(ShopLogin shopLogin) {
        HashMap<String, String> res = new HashMap<>();
        ShopLogin shopInfo = shopMapper.shopInfoByUserNameAndPhone(shopLogin);
        if (shopInfo==null){
            throw new BizException(ApiResultCode.FAILED_ACCOUNT);
        }
        if (CommonUtils.compare(shopInfo.getPassword(), Md5Utils.hash(shopLogin.getPassword()))){

            res.put("token",generateToken(shopInfo));
        }else {
            throw new BizException(ApiResultCode.FAILED_LOGIN);
        }
        return ApiResult.newSuccess(res);

    }

    public String generateToken(ShopLogin shopLogin) {
        String newToken = UUID.randomUUID().toString().replace("-", "");
        HashMap<String, Object> loginInfo = new HashMap<>();
        loginInfo.put("time", new Date().getTime());
        loginInfo.put("shopId", shopLogin.getShopId());
        //获取上次token
        String oldToken = redisUtil.get(fex_shop + shopLogin.getShopId());
        //清除上次登录token
        redisUtil.del(fex_shop+oldToken,fex_shop+shopLogin.getShopId());
        redisUtil.set(fex_shop + shopLogin.getShopId(), newToken, tokenTime);
        redisUtil.set(fex_shop +newToken, JSON.toJSONString(loginInfo), tokenTime);
        return newToken;
    }

    public ShopLoginDto shopInfo() {
        String shopId = commonUtils.getShopId(request);
        ShopLogin shopLogin = new ShopLogin();
        shopLogin.setShopId(Integer.parseInt(shopId));
        //根据商家id获取商家角色信息
        ShopLoginDto shopLoginDto = shopMapper.getShopInfo(shopLogin);
        List<Object> permissionMenu = getPermissionMenu(Integer.parseInt(shopId),"CM",commonUtils.getToken(request));
        shopLoginDto.setPermissionMenus(permissionMenu);
        ArrayList<String> strings = new ArrayList<>();
        strings.add(shopLoginDto.getType());
        shopLoginDto.setRoles(strings);
        return shopLoginDto;

    }
    //获取权限菜单
    public List<Object> getPermissionMenu(Integer shopId,String type,String token){
        if (redisUtil.hasKey(fex_shop_permission+token)){
            return (List<Object>) redisUtil.lGetIndex(fex_shop_permission+token,0);
        }else {
            PermissionMenuDto permissionMenu = new PermissionMenuDto();
            permissionMenu.setShopId(shopId);
            permissionMenu.setType(type);
            List<PermissionMenuDto> menuAndPermission = shopMapper.getMenuAndPermission(permissionMenu);
            List<Object> tree = Collections.singletonList(TreeUtil.tree(menuAndPermission));
            redisUtil.lSet(fex_shop_permission+token,tree,permissionTime);
        }
        return  (List<Object>) redisUtil.lGetIndex(fex_shop_permission+token,0);



    }
    public ArrayList<String> getPermission(Integer shopId){
        ArrayList<String> permissions = new ArrayList<>();
        PermissionMenuDto permissionMenuDto = new PermissionMenuDto();
        permissionMenuDto.setShopId(shopId);
        permissionMenuDto.setType("B");
        List<PermissionMenuDto> menuAndPermission = shopMapper.getMenuAndPermission(permissionMenuDto);
        if (menuAndPermission.size()>0){
            permissions = shopMapper.getPermission(menuAndPermission);
            return permissions;
        }
        return permissions;
    }
    //失效权限菜单
    public void losePermissionMenu(){
        String token = commonUtils.getToken(request);
        redisUtil.lLeftPop(fex_shop_permission+token);
    }
    public void loseToken(){
        String shopId = commonUtils.getShopId(request);
        String token = commonUtils.getToken(request);
        redisUtil.del(fex_shop+shopId);
        redisUtil.del(fex_shop+token);
    }



    public Object cityCode() {
       return shopMapper.selectRegionCity();
    }
}
